﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain;
using WebNext.UI.Properties;
using WebNext.Domain.Entities;
using WebNext.UI.Models.Tags;
using WebNext.UI.Utils;

namespace WebNext.UI.Models.Entries
{
	public class EntryEditViewModel : EntryViewModel
	{
		public bool IsTitleValid
		{
			get;
			private set;
		}

		public void UpdateElementsOrder()
		{
			for (int i = 0; i < this.Elements.Count; i++)
			{
				this.Elements[i].Order = i + 1;
			}
		}

		public ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();

			if (string.IsNullOrWhiteSpace(this.Title))
			{
				result.AddError(Resources.EntryTitleCannotBeEmpty);
				this.IsTitleValid = false;
			}
			else if (this.Title.Length > Entry.MaxTitleLength)
			{
				result.AddError(Resources.EntryTitleTooLong, Entry.MaxTitleLength);
				this.IsTitleValid = false;
			}

			foreach (EntryElementViewModel elementModel in this.Elements)
			{
				result.Merge(elementModel.Validate());
			}
			return result;
		}

		public IList<TagViewModel> AllTags
		{
			get;
			private set;
		}

		public EntryEditViewModel(int id, MainViewType viewType, string title, bool isLogged) : base(id, viewType, title, isLogged)
		{
			this.IsTitleValid = true;
			this.AllTags = new List<TagViewModel>();
		}

		public EntryEditViewModel(Entry entry, IEnumerable<Tag> tags, bool isLogged) : base(entry, isLogged)
		{
			this.IsTitleValid = true;
			this.AllTags = new List<TagViewModel>();
		}

		public void LoadAllTags(IEnumerable<Tag> allTags)
		{
			this.AllTags = allTags.Select(t => new TagViewModel(t)).ToList();
		}
	}
}